import { useLayoutEffect, useState } from 'react';
import { Router, BrowserRouterProps } from 'react-router-dom';
import type { BrowserHistory } from 'history';

type Props = BrowserRouterProps & {
  history: BrowserHistory;
};
// 参考：
// https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/index.tsx#L133-L160
const CustomRouter = ({ history, ...restProps }: Props) => {
  const [state, setState] = useState({
    // 路由跳转类型，比如，push / replace
    action: history.action,
    location: history.location,
  });

  // useEffect vs. useLayoutEffect
  // https://codesandbox.io/s/uselayouteffect-vs-useeffect-1-v4f4yh?file=/src/App.js
  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...restProps}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};

export default CustomRouter;
